<template>
  <div class="meituan-container">
    <!-- 顶部导航 -->
    <el-header class="meituan-header">
      <div class="header-logo">
        <img
          src="https://images.91160.com/unit/notice/2016082209452967277.jpg"
          alt="医疗产品购买"
        />
        <span class="header-title">医疗产品购买</span>
      </div>
      <div class="search-container">
    <el-input
      placeholder="搜索产品或套餐"
      class="search-input"
      v-model="searchQuery"
      @input="searchProducts"
    ></el-input>
  </div>
      <div class="welcome-button">
    <el-button type="primary" @click="goToWelcome">返回主界面</el-button>
  </div>
    </el-header>

    <!-- 内容区域 -->
    <el-container>
      <!-- 左侧分类 -->
      <el-aside width="200px">
        <el-menu
          :default-active="activeCategory"
          @select="handleCategorySelect"
          @open="handleOpen"
          :collapse-transition="false"
          background-color="#f0f0f0"
          text-color="#333"
          active-text-color="#72caed"
          unique-opened
        >
          <el-submenu index="1">
            <template slot="title">
              <i class="el-icon-shopping-bag-1"></i>
              <span>产品</span>
            </template>
            <el-menu-item
              v-for="category in productCategories"
              :key="category.id"
              :index="category.id"
            >
              {{ category.name }}
            </el-menu-item>
          </el-submenu>
          <el-submenu index="2">
            <template slot="title">
              <i class="el-icon-goods"></i>
              <span>套餐</span>
            </template>
            <el-menu-item
              v-for="category in setmealCategories"
              :key="category.id"
              :index="category.id"
            >
              {{ category.name }}
            </el-menu-item>
          </el-submenu>
        </el-menu>
      </el-aside>

      <!-- 中间商品展示 -->
      <el-main>
        <div class="product-list">
          <el-card
            v-for="product in filteredProducts"
            :key="product.id"
            class="product-item"
          >
            <img :src="product.image" class="product-image" />
            <div class="product-info">
              <p class="product-name">{{ product.name }}</p>
              <p class="product-price">价格: ¥{{ product.price }}</p>
              <div class="product-actions">
                <el-button type="success" @click="addToCart(product)">
                  加入购物车
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
        <div
          v-if="filteredProducts.length === 0 && searchQuery"
          class="no-results"
        >
          没有找到匹配的产品或套餐。
        </div>
        <div
          v-if="filteredProducts.length === 0 && !searchQuery"
          class="no-results"
        >
          请选择左侧分类或搜索您需要的商品。
        </div>
      </el-main>

      <!-- 右侧购物车 -->
      <el-aside width="300px">
        <div class="cart-header">
          <h3>购物车</h3>
        </div>
        <el-table :data="cart" :row-key="(item) => item.id">
          <el-table-column prop="name" label="商品名称"></el-table-column>
          <el-table-column prop="price" label="价格"></el-table-column>
          <!-- 修改 price 为 amount -->
          <el-table-column prop="number" label="数量"></el-table-column>
          <!-- 修改 quantity 为 number -->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button-group>
                <el-button
                  size="mini"
                  @click="addOneToCart(scope.row)"
                  icon="el-icon-plus"
                ></el-button>
                <el-button
                  size="mini"
                  @click="removeFromCart(scope.row)"
                  icon="el-icon-minus"
                ></el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="cart.length > 0" class="cart-summary">
          <p>总价: ¥{{ totalPrice.toFixed(2) }}</p>
          <el-button type="danger" @click="clean">清空购物车</el-button>
          <el-button type="primary" @click="checkout">去结算</el-button>
        </div>
         
        <el-alert
          class="health-tip"
          title="健康提示"
          type="info"
          description="定期体检是预防疾病的重要手段。请根据自身情况选择合适的体检套餐。"
          show-icon
        >
        </el-alert>
      </el-aside>
    </el-container>
    <!-- 底部信息 -->
    <el-footer class="meituan-footer">
      <div class="footer-content">
        <p>© 2023 医疗产品购买平台. All Rights Reserved.</p>
        <p>
          联系我们：<a href="mailto:support@medicalplatform.com"
            >support@medicalplatform.com</a
          >
        </p>
      </div>
    </el-footer>

     <el-dialog
    title="选择收货地址"
    :visible.sync="addressDialogVisible"
    width="50%"
    @close="handleAddressClose"
  >
    <el-radio-group v-model="selectedAddressId">
      <el-radio
        v-for="address in addressList"
        :key="address.id"
        :label="address.id"
      >
        <div class="address-item">
          <p>{{ address.consignee }} - {{ address.phone }}</p>
          <p>{{ address.detail }}</p>
        </div>
      </el-radio>
    </el-radio-group>

    <!-- 地址选择确认和取消按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="addressDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmAddress">确定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>


export default {
   
  data() {
    return {
      productCategories: [],
      setmealCategories: [],
      products: [],
      searchQuery: "",
      activeCategory: "1",
      selectedType: 1,
      cart: [],
      addressBookId: null,
      deliveryStatus: 0,
      estimatedDeliveryTime: null,
      orderSubmitDto: {
        addressBookId: 0,
        totalPrice: 0,
        deliveryStatus: 0,
        estimatedDeliveryTime: null,
        payMethod: 0,
        remark: null,
      },
      orderNumber: null,
      orderTime: null,
      orderId: null,

      addressDialogVisible: false, // 控制地址对话框的显示
    addressList: [], // 用户地址列表
    selectedAddressId: null, // 用户选择的地址ID
    };
  },
  computed: {
    filteredProducts() {
      if (this.products.length === 0) {
        return [{ name: "当前分类下无商品", price: 0 }];
      }
      let filtered = this.products;
      if (this.searchQuery) {
        filtered = this.products.filter((product) =>
          product.name.toLowerCase().includes(this.searchQuery.toLowerCase())
        );
      }
      return filtered;
    },
    totalPrice() {
      return this.cart.reduce(
        (total, item) => total + item.price * item.number,
        0
      );
    },
  },
  methods: {
    handleOpen(key) {
      if (key === "1") {
        this.selectedType = 1;
      } else {
        this.selectedType = 2;
      }
    },
    handleCategorySelect(categoryId) {
      this.activeCategory = categoryId;
      if (this.selectedType === 2) {
        // 套餐分类时，访问 /selectByCategoryId 接口
        this.$http
          .get("/webPage/setmeal/selectByCategoryId", {
            params: {
              categoryId: categoryId,
            },
          })
          .then((res) => {
            this.products = res.data.data; // 更新套餐商品展示
          });
      } else {
        // 普通商品分类时，访问商品查询接口
        this.$http
          .get("/webPage/product/pageSelect", {
            params: {
              page: 1,
              pageSize: 9999999,
              categoryId: categoryId,
              status: 1,
            },
          })
          .then((res) => {
            this.products = res.data.data.records; // 更新商品展示
          });
      }
      this.scrollToProducts();
    },
    addToCart(product) {
      if (this.selectedType === 1) {
        this.$http.post("/webPage/shoppingCart/add", {
          productId: product.id,
          setmealId: null,
        });
      } else {
        this.$http.post("/webPage/shoppingCart/add", {
          setmealId: product.id,
          productId: null,
        });
      }

      const cartItem = this.cart.find((item) => item.id === product.id);
      if (cartItem) {
        cartItem.number += 1;
      } else {
        this.cart.push({ ...product, number: 1 });
      }
    },
    addOneToCart(product) {
      if (this.selectedType === 1) {
        this.$http.post("/webPage/shoppingCart/add", {
          productId: product.id,
          setmealId: null,
        });
      } else {
        this.$http.post("/webPage/shoppingCart/add", {
          setmealId: product.id,
          productId: null,
        });
      }

      const cartItem = this.cart.find((item) => item.id === product.id);
      if (cartItem) {
        cartItem.number += 1;
      } else {
        this.cart.push({ ...product, number: 1 });
      }
    },
    removeFromCart(product) {
      
       if (this.selectedType === 1) {
        this.$http.post("/webPage/shoppingCart/sub", {
          productId: product.id,
          setmealId: null,
        });
      } else {
        this.$http.post("/webPage/shoppingCart/sub", {
          setmealId: product.id,
          productId: null,
        });
      }
      const index = this.cart.findIndex((item) => item.id === product.id);
      if (index !== -1) {
        if (this.cart[index].number > 1) {
          this.cart[index].number -= 1;
        } else {
          this.cart.splice(index, 1);
        }
      }
    },
    searchProducts() {
      // 在搜索框输入时，实时过滤产品
      this.filteredProducts = this.products.filter((product) =>
        product.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
    },

    checkout() {
       this.addressDialogVisible = true;
      this.$http.get("/webPage/addressBook/getAll").then((res) => {
      this.addressList = res.data.data;
    });

      
    },
    confirmAddress() {
    // 检查是否选择了地址
    if (!this.selectedAddressId) {
      this.$message.error("请选择一个收货地址");
      return;
    }

    // 设置订单地址并提交订单
    this.orderSubmitDto.addressBookId = this.selectedAddressId;
    this.orderSubmitDto.totalPrice = this.totalPrice;
    this.orderSubmitDto.deliveryStatus = 1;

    this.$http.post("/webPage/order/submit", this.orderSubmitDto).then((res) => {
      // 订单数据处理逻辑...
      this.addressDialogVisible = false; // 关闭地址选择框
      const orderData = {
        id: res.data.data.id,
        items: this.cart,
        orderNumber: res.data.data.orderNumber,
        totalPrice: this.totalPrice,
        orderTime: res.data.data.orderTime,
      };
      this.$router.push({
        name: "payment",
        params: { orderData: JSON.stringify(orderData) },
      });
    });
  },

  handleAddressClose() {
    this.addressDialogVisible = false; // 关闭对话框
  },
    clean() {
      this.$confirm("确定要清空购物车吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 清空购物车请求
          this.$http.delete("/webPage/shoppingCart/clean").then(() => {
            this.cart = []; // 清空购物车数据
            this.$message({
              type: "success",
              message: "购物车已清空",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消清空",
          });
        });
    },
    scrollToProducts() {
      // 滚动到商品列表区域
      this.$nextTick(() => {
        document.querySelector(".product-list").scrollIntoView({
          behavior: "smooth",
        });
      });
    },
    goToWelcome() {
      this.$router.push('/welcome');
    }
  },
  created() {
    this.$http
      .get("/webPage/product/pageSelect", {
        params: {
          page: 1,
          pageSize: 9999999,
          categoryId: 1,
          status: 1,
        },
      })
      .then((res) => {
        this.products = res.data.data.records;
      });
    this.$http
      .get("/webPage/category/pageSelect", {
        params: {
          type: 1,
          page: 1,
          pageSize: 999999,
        },
      })
      .then((res) => {
        this.productCategories = res.data.data.records;
      });
    this.$http
      .get("/webPage/category/pageSelect", {
        params: {
          type: 2,
          page: 1,
          pageSize: 999999,
        },
      })
      .then((res) => {
        this.setmealCategories = res.data.data.records;
      });
    this.$http.get("/webPage/shoppingCart/get").then((res) => {
      this.cart = res.data.data;
    });
  },
};
</script>

<style scoped>

.address-item {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-bottom: 10px;
}

.meituan-container {
  min-height: 100vh;
  background-color: #f5f5f5; /* 浅灰色背景 */
  font-family: "Helvetica Neue", Arial, sans-serif;
}
.meituan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: RGB(52,162,219); /* 蓝色头部 */
  color: #fff;
  height: 60px;
  font-weight: bold;
}

.header-logo img {
  height: 40px;
}
.header-logo {
  display: flex;
  align-items: center;
}
.search-container {
  flex: 1; /* 占据中间可用空间 */
  display: flex;
  justify-content: center;
  margin-right: 20px;
}

.search-input {
  width: 300px;
}
.product-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 20px;
}

.product-item {
  width: 250px;
  border: 1px solid #ccc;
  border-radius: 5px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-info {
  padding: 10px;
  text-align: center;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.product-price {
  margin-bottom: 10px;
}

.product-actions {
  display: flex;
  justify-content: center; /* 居中商品展示按钮 */
  margin-top: 10px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ccc;
}

.cart-summary {
  text-align: right;
  padding: 10px;
}

.el-aside {
  position: sticky;
  top: 0;
  height: calc(100vh - 60px); /* 调整高度，减去头部高度 */
  overflow-y: auto;
}

.health-tip {
  margin-top: 20px;
  font-size: 14px;
}

.no-results {
  text-align: center;
  font-size: 18px;
  padding: 20px 0;
}

.meituan-footer {
  background-color: #f0f0f0; /* 浅灰色底部 */
  padding: 20px;
  text-align: center;
}

.footer-content {
  font-size: 14px;
}

.footer-content a {
  color: #007bff; /* 蓝色链接 */
  text-decoration: none;
}

.footer-content a:hover {
  text-decoration: underline;
}

.welcome-button {
  margin-left: auto;
  display: flex;
  align-items: center;
}
</style>